Micron Document




Python syntax and semantics
part 24/45 · 74.8 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
The Quicksort algorithm can be expressed elegantly (albeit inefficiently) using list comprehensions:

def qsort(L):
if L == []:
return []
pivot = L[0]
return (qsort([x for x in L[1:] if x < pivot]) +
[pivot] +
qsort([x for x in L[1:] if x >= pivot]))

Python 2.7+cite-ref-21[17] also supports set comprehensionscite-ref-22[18] and dictionary comprehensions.cite-ref-23[19]

First-class functions

In Python, functions are first-class objects that can be created and passed around dynamically.

Python's limited support for anonymous functions is the lambda construct. An example is the anonymous function which squares its input, called with the argument of 5:

f = lambda x: x**2
f(5)

Lambdas are limited to containing an expression rather than statements, although control flow can still be implemented less elegantly within lambda by using short-circuiting,cite-ref-24[20] and more idiomatically with conditional expressions.cite-ref-25[21]

Closures

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────